package com.yq.admin.service.impl;

import com.yq.admin.qo.ProductQueryVO;
import com.yq.admin.util.ProductQueryTOUtil;
import com.yq.admin.util.ProductTOUtil;
import com.yq.admin.vo.ProductVO;
import com.yq.api.comm.ResultHandle;
import com.yq.api.dto.ProductTO;
import com.yq.api.exception.product.AddProductException;
import com.yq.api.exception.product.QueryProductException;
import com.yq.api.qto.ProductQueryTO;
import com.yq.api.service.ProductServiceFacade;
import com.yq.comm.constant.ContextConstants;
import com.yq.admin.service.ProductFrontService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Created by zhouyanqun on 2016/8/12.
 */
@Service("productAdminService")
public class ProductFrontServiceImpl implements ProductFrontService {
    @Resource(name = "productServiceFacade")
    private ProductServiceFacade productServiceFacade;
    private static final Log log = LogFactory.getLog(ProductFrontServiceImpl.class);
    /**
     * 新建产品
     *
     */
    public void addProduct(ProductVO productVO) {
        if(productVO == null){
            String msg = "产品信息为空，不能创建";
            log.error(msg);
            throw new AddProductException(msg);
        }
        String imageFilePath = saveImageFileForProduct(productVO);
        productVO.setPrimaryImageUrl(imageFilePath);

        ProductTO productTO = ProductTOUtil.toProductTO(productVO);
        ResultHandle<ProductTO> resultHandle = productServiceFacade.addProduct(productTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new AddProductException(resultHandle.getMessage());
        }
        ProductTOUtil.writeBack(productTO, productVO);
    }

    public ProductVO queryProduct(Long productId) {
        if(productId == null || productId < 0){
            throw new QueryProductException("id can't be empty");
        }
        ResultHandle<ProductTO> resultHandle = productServiceFacade.getProductByProductId(productId);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new QueryProductException(resultHandle.getMessage());
        }
        return ProductTOUtil.toProductVO(resultHandle.getResultContent());
    }

    public List<ProductVO> queryProductList(ProductQueryVO productQueryVO) {
        if (productQueryVO == null) {
            return null;
        }
        ProductQueryTO productQueryTO = ProductQueryTOUtil.toProductQueryTO(productQueryVO);
        ResultHandle<List<ProductTO>> resultHandle = productServiceFacade.getProducts(productQueryTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new QueryProductException(resultHandle.getMessage());
        }
        return ProductTOUtil.toProductVOList(resultHandle.getResultContent());
    }

    /**
     * 保存产品信息中的图片
     * @return 保存好的图片的路径
     * */
    private String saveImageFileForProduct(ProductVO productVO){
        MultipartFile primaryImage = productVO.getPrimaryImage();
        //文件的初始名(一般是客户端的文件名)
        String originalFilename = primaryImage.getOriginalFilename();
        log.info("begin to upload file " + originalFilename);
        //上传到服务器端的文件路径
        String uploadFilePath = generateFilePath(originalFilename);
        File imageFile = new File(uploadFilePath);
        if(!imageFile.exists()){
            imageFile.mkdirs();
        }
        log.info("generated file path is " + uploadFilePath);
        try {
            primaryImage.transferTo(imageFile);
        } catch (IOException e) {
            log.error("Error occurs while try to save image file " + originalFilename, e);
            throw new AddProductException(e.getMessage());
        }
        //标准的文件名
        String canonicalFileName = null;
        try {
            canonicalFileName = imageFile.getCanonicalPath();
        } catch (IOException e) {
            log.error("Error catch canonical path for upload file ",e);
        }
        log.info("Have completed upload file " + originalFilename + ", canonical path is " + canonicalFileName);
        return uploadFilePath;
    }

    /**
     * 生成图片文件的路径
     * @param originalFilename: 文件的初始名(一般是客户端的文件名)
     * */
    private String generateFilePath(String originalFilename){
        return  ContextConstants.FILE_UPLOAD_PATH + "/uploadFile_" + UUID.randomUUID() + "_" + originalFilename;
    }
}
